package com.itqn.servlet;

import com.alibaba.fastjson.JSONArray;
import com.itqn.pojo.Member;
import com.itqn.pojo.PageBean;
import com.itqn.service.Impl.MemberServiceImpl;
import com.itqn.service.MemberService;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(value = "/memberQuery")
public class MemberServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 解决post提交中文乱码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        //获取参数
        String name = request.getParameter("name");
        String cartNumber = request.getParameter("cartNumber");
        Integer totalAmount = null;
        if (!request.getParameter("totalAmount").equals("")) {
            totalAmount = Integer.valueOf(request.getParameter("totalAmount"));
            totalAmount = totalAmount <= 0 ? null : totalAmount;
        }
        Integer page = Integer.valueOf(request.getParameter("page"));
        page = page == null ? 1 : page;
        Integer pageSize = Integer.valueOf(request.getParameter("pageSize"));
        pageSize = pageSize == null ? 5 : pageSize;

        // 创建业务逻辑层对象
        MemberService memberService=new MemberServiceImpl();
        // 使用业务逻辑层对象调用查询所有的方法
        PageBean<Member> pageQuery = memberService.query(name, cartNumber, totalAmount, pageSize, page);
        String str = JSONArray.toJSONString(pageQuery);
        PrintWriter writer = response.getWriter();
        writer.write(str);
    }
}